package com.orchard.orchardfarmmanagementsystem.exception;

import com.orchard.orchardfarmmanagementsystem.utils.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    // 处理未授权 (403)
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ResponseBody
    public Result<?> handleAccessDeniedException(AccessDeniedException ex) {
        return Result.error(403, "你没有该权限，请联系管理员获取更多权限。");
    }

    // 处理认证失败 (401)
    @ExceptionHandler(AuthenticationCredentialsNotFoundException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public Result<?> handleAuthenticationException(AuthenticationCredentialsNotFoundException ex) {
        return Result.error(401, "请先登录或注册以继续。");
    }

    // 您可以添加更多的异常处理方法来处理其他类型的异常
}